package com.example.aicloud.controller;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aicloud.entity.dto.UserDTO;
import com.example.aicloud.entity.User;
import com.example.aicloud.service.impl.UserServiceImpl;
import com.example.aicloud.util.NameUtil;
import com.example.aicloud.util.ResponseEntity;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
@Tag(name = "用户控制器")
public class UserController {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserServiceImpl userService;
    @Value("${jwt.secret}")
    private String jwtSecret;
    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     *登录 login 方法
     */
    @PostMapping("/login")
    public ResponseEntity login(@Validated UserDTO userDTO, HttpServletRequest request) {

        //1. 验证校验码
        String redisCaptchaKey = NameUtil.getCaptchaName(request);
        String redisCaptcha = (String) redisTemplate.opsForValue().get(redisCaptchaKey);
        if (!StringUtils.hasLength(redisCaptcha) || !redisCaptcha.equalsIgnoreCase(userDTO.getCaptcha()) ){
            return ResponseEntity.fail("验证码错误!");
        }

        //2. 验证用户名密码是否正确
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        User user = userService.getOne(queryWrapper);
        if (user!=null && passwordEncoder.matches(userDTO.getPassword(),user.getPassword())){
            // 生成JWT
            HashMap<String,Object> payLoad =new HashMap<>();
            payLoad.put("uid",user.getUid());
            payLoad.put("username",user.getUsername());
            HashMap<String ,String> result =new HashMap<>();
            result.put("jwt",JWTUtil.createToken(payLoad,jwtSecret.getBytes()));
            result.put("username",user.getUsername());
            return ResponseEntity.success(result);
        }
        return ResponseEntity.fail("用户名或密码错误!");
    }

    /**
     * 注册方法
     */
    @PostMapping("/register")
    public ResponseEntity register(@Validated User user){
        // 将密码进行加盐处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean result = userService.save(user);
        if (result){
            return ResponseEntity.success(result);
        }
        return ResponseEntity.fail("未知错误!");
    }
}
